import dataSimpleStringCell from './dataSimpleStringCell.js'
// import { v4 as uuidv4 } from 'uuid'
export default class generaSheet {

	async fillData(dsObj, range, columnMap, isClearTemplate = true) {
		// 先get复制，
		const that = this
		let dataTable = dsObj.dataTables[0]
		let dsArr = []	//	二维数组
		dataTable?.dataRows.forEach(item => {
			dsArr.push(item.rowData)
		})

		let startCoordObj = that.getCoordObj(range)[0]
		let endCoordObj = that.getCoordObj(range)[1]

		console.log(startCoordObj, endCoordObj, '模板坐标', range)

		if (isClearTemplate) {
			// 删除模板行，新增加一
			// 新增dataTable.length行
			if (dsArr.length == 0) {
				return 0
			} else if (dsArr.length > 1) {
				that.insertRowAfter(startCoordObj.r + 1, dsArr.length - 1)
				for (let i = 0; i < dsArr.length; i++) {
					// 复制模板行
					let row = [startCoordObj.r + i, endCoordObj.r + i]
					let column = [startCoordObj.c, endCoordObj.c]
					let getRange = { row: row, column: column }
					await that.getRangeValue(getRange)

					// 粘贴
					let row2 = [startCoordObj.r + i + 1, endCoordObj.r + i + 1]
					let column2 = [startCoordObj.c, endCoordObj.c]
					let setRange = { row: row2, column: column2 }

					await that.setRangeValue(setRange)
				}
				let tag = 0
				for (let i = startCoordObj.r; i < startCoordObj.r + dsArr.length; i++) {
					if (tag < dsArr.length) {
						let arr = dsArr[tag]	//map中的一行
						arr.forEach(item => {
							let c = columnMap[item.columnName]
							console.log(i + 1, c, '设置单元格值');
							that.setCellValue(i + 1, c, item.value)
						})
					}
					tag += 1
				}
			} else if (dsArr.length == 1) {
				dsArr[0].forEach((item) => {
					let c = columnMap[item.columnName]
					that.setCellValue(startCoordObj.r + 1, c, item.value)
				})

			}

		} else {
			// 不删模板行
			// 新增dataTable.length行
			if (dsArr.length == 0) {
				return 0
			} else if (dsArr.length >= 1) {
				that.insertRowAfter(startCoordObj.r + 1, dsArr.length)
			}

			for (let i = 0; i < dsArr.length; i++) {
				// 复制模板行
				let row = [startCoordObj.r + i, endCoordObj.r + i]
				let column = [startCoordObj.c, endCoordObj.c]
				let getRange = { row: row, column: column }
				await that.getRangeValue(getRange)

				// 粘贴
				let row2 = [startCoordObj.r + i + 1, endCoordObj.r + i + 1]
				let column2 = [startCoordObj.c, endCoordObj.c]
				let setRange = { row: row2, column: column2 }
				await that.setRangeValue(setRange)
			}


			let tag = 0
			for (let i = startCoordObj.r; i < startCoordObj.r + dsArr.length; i++) {
				if (tag < dsArr.length) {
					let arr = dsArr[tag]	//map中的一行
					arr.forEach(item => {
						let c = columnMap[item.columnName]
						// 模板行的下一行开始设置
						that.setCellValue(i + 2, c, item.value)
					})
				}
				tag += 1
			}
		}

		// 返回dsArr.length
		return dsArr.length
	}

	/**
	 * @description: 根据ds的表数据，填充模板文件
	 * @param {Object | Array} dsObj ds类
	 * @param {String} titleRange 标题行区域
	 * @param {String} templateRange 模板行区域
	 * @param {Boolean} isClearTemplate 是否删除模板行
	 * @param {Number} initialRow 数据插入起始行
	 * @return {Number} 返回插入了几行数据
	 */
	async fillDataComplex (dsObj, titleRange, templateRange, isClearTemplate, initialRow) {
		let that = this
		let dataTable
		let dsArr = []	//	二维数组
		// 判断dsObj是否为数组
		if (dsObj.constructor === Array) {
			dsObj.forEach(item => {
				if (item) {
					dataTable = item.dataTables[0]
					dataTable?.dataRows.forEach(i => {
						dsArr.push(i.rowData)
					})
				}
			})
		} else if (dsObj) {
			dataTable = dsObj.dataTables[0]
			dataTable?.dataRows.forEach(item => {
				dsArr.push(item.rowData)
			})
		} else if (dsObj === undefined) {
			alert('dsObj不能为undefined')
			return false
		}
		// 获取标题行列号
		let titleList = [] // ds标题list
		dataTable.dataColumns.forEach(item => {
			titleList.push(item.name)
		})
		let  rangeValList = [] // xlg标题区间list
		window.codelist.getRangeValueList(titleRange, that.order)[0].forEach(item => {
			rangeValList.push(item ? item.m : null)
		})
		let titleDataList = [] 
		titleList.forEach(item => {
			rangeValList.forEach((i, k) => {
				if (item === i) {
					let obj = {
						title: i, // 标题
						columnIndex: parseInt(that.letterToNum(titleRange.charAt())) + k + 1 // 列号
					}
					titleDataList.push(obj)
				}
			})
		})
		let beforeContentRange = templateRange ? templateRange : titleRange
		// 获取插入起始行
		let rowList = beforeContentRange.split(/[^\d]/g).filter(item => {
			return item !== ""
		})
		let colList = beforeContentRange.split(/[^a-zA-Z]/g).filter(item => {
			return item !== ""
		})
		if (rowList[0] !== rowList[1]) {
			alert('模板行不支持多行，请修改模板行参数')
			return false
		}
		let rowIndex = Number(rowList[0]) // 有模板行则为模板行，没有则为标题行
		window.codelist.insertRowAfter(null, initialRow ? initialRow - 1 : rowIndex, dsArr.length, that.order)
		let startRow = initialRow ? initialRow : rowIndex + 1
		let endRow = startRow - 1 + dsArr.length
		let pasteRange = `${colList[0]}${startRow}:${colList[1]}${endRow}`
		if (templateRange) {
			// 有模板行的情况下，进行模板行的复制粘贴
			await window.codelist.getRangeValue(null, null, that.order)
			await window.codelist.setRangeValue(null, templateRange, pasteRange, false, that.order)
		}
		for (let key = 0; key < dsArr.length; key++) {
			let row = initialRow ? initialRow + key : Number(rowList[0]) + key + 1
			dsArr[key].forEach(i => {
				let titleItem = titleDataList.find(j => {
					return j.title === i.columnName
				})
				if (titleItem) {
					let column = titleItem.columnIndex
					window.codelist.setCellValue2(null, row, column, i.value, that.order)
				}
			})
		}
		if (isClearTemplate) {
			window.codelist.deleteRow(null, rowIndex, rowIndex, that.order)
		}
		return dsArr.length // 返回插入了几行数据
	}

	getCoordObj(range) {
		const that = this
		let coordSplitArr = range.split(':')
		let objArr = []

		coordSplitArr.forEach((item) => {
			let obj = {}

			let numMatchArr = item.match(/\d+/g)
			let letterMatchArr = item.match(/[a-zA-Z]+/g)

			obj.r = parseInt(numMatchArr[0]) - 1
			obj.c = parseInt(that.letterToNum(letterMatchArr[0]))
			objArr.push(obj)

		})
		return objArr
	}
	letterToNum(item) {
		let num = ''
		for (let i = 0; i < item.length; ++i) {
			num += item.toUpperCase().charCodeAt(i) - 65//小写字母需要转为大写之后再转
		}
		return num
	}


	hideRow(rowStart = 0, rowEnd = 0) {
		const that = this

		that.xlgObj.xlgJson = window.codelist.hideRow(that.xlgObj.xlgJson, rowStart, rowEnd, that.order)
		return that
	}


	setRangeFilter(type = 'open', range = 'A1:A2') {
		const that = this
		if (type == 'open' || type == 'close') {
			// 打开或关闭筛选

			that.xlgObj.xlgJson = window.codelist.setRangeFilter(that.xlgObj.xlgJson, type, range, that.order)
		} else {
			throw new Error('type仅能为open或close')
		}
		return that
	}

	// setCellValue(row = 1, column = 'a', value = 'setCellValue请输入第三个参数') {
	// 	const that = this

	// 	that.xlgObj.xlgJson = window.codelist.setCellValue(that.xlgObj.xlgJson, row, column, value, that.order)
	// 	return that
	// }

	setCellValue(row = 1, column = 'a', value) {
		const that = this
		if (value === undefined && typeof row === 'string') {
			let cell = row
			let value = column
			that.xlgObj.xlgJson = window.codelist.setCellValue3(that.xlgObj.xlgJson, cell, value, that.order)
		} else {
			that.xlgObj.xlgJson = window.codelist.setCellValue2(that.xlgObj.xlgJson, row, column, value, that.order)
		}
		return that
	}

	getCellValue(row = 1, column = 'a') {
		return window.codelist.getCellValue(this.xlgObj.xlgJson, row, column, this.order)
	}

	setColumnWidth (colWidthObj) {
		window.codelist.setColumnWidth(colWidthObj, this.order)
	}

	async getRangeValue(range = 'A1:A2') {
		const that = this

		let result = await window.codelist.getRangeValue(that.xlgObj.xlgJson, range, that.order)
		return result
	}
	async setRangeValue(range = 'A1:A2') {
		const that = this
		that.xlgObj.xlgJson = await window.codelist.setRangeValue(that.xlgObj.xlgJson, range, that.order)
		return that
	}
	copyRegion(from, to, isMerge) {
		const that = this
		// 获取选区值
		window.codelist.getRangeValue(that.xlgObj.xlgJson, from, that.order)
		// 对选区赋值
		window.codelist.setRangeValue(that.xlgObj.xlgJson, from, to, isMerge, that.order)
		return that
	}

	// 向上新增
	insertRowBefore(row = 0, number = 1) {
		const that = this
		if (number == '0') {
			return 
			// throw new Error('新增number至少为1')
		}

		that.xlgObj.xlgJson = window.codelist.insertRowBefore(that.xlgObj.xlgJson, row, number, that.order)
		return that
	}

	// 向下新增
	insertRowAfter(row = 0, number = 1) {
		const that = this
		if (number == '0') {
			return 
			// throw new Error('新增number至少为1')
		}
		that.xlgObj.xlgJson = window.codelist.insertRowAfter(that.xlgObj.xlgJson, row, number, that.order)
		return that
	}


	deleteRow(startRow = 0, endRow = 0) {
		const that = this
		that.xlgObj.xlgJson = window.codelist.deleteRow(that.xlgObj.xlgJson, startRow, endRow, that.order)
		return that
	}

	/**
	 * @description: 选定的范围开启多列自定义排序功能
	 * @param {Array} sort 列设置，设置需要排序的列索引和排序方式，格式如：[{ i:1,sort:'asc' },{ i:2,sort:'des' }]
	 * @param {String} range 选区范围,支持选区的格式
	 */
	sort (sort, range) {
		window.codelist.sort(sort, range, this.order)
	}

	constructor(name, index) {
		if (name || index) {
			this.name = name
			this.color = ""
			this.index = index
			this.order = index + ''
			if (index === 0) {
				this.status = '1'
			} else {
				this.status = '0'
			}
		} else {
			alert("Sheet页名称 或 数据页 下标 不允许为空")
		}
	}
	config = {}
	data = this.initData()
	celldata = []
	calcChain = []
	jfgird_select_save = []
	luckysheet_select_save = []
	visibledatarow = []
	visibledatacolumn = []
	ch_width = 4560
	rh_height = 2080
	luckysheet_selection_range = []
	zoomRatio = 1


	initData() {
		let data = [];
		for (let i = 0; i < 100; i++) {
			let row = [];
			for (let j = 0; j < 60; j++) {
				row.push(null)
			}
			data.push(row)
		}
	}
	createSimpleStringCell(r, c, v) {
		if (Object.keys(this.getCelldata(r, c)).length) {
			// alert("数据区块"+columnName+"已存在数据列"+columnName+"，不允许重复添加")
		} else {
			let cell = new dataSimpleStringCell(r, c, v);
			this.celldata.push(cell);
		}
	}
	getCelldata(r, c) {
		const celldata = this.getCelldata.filter(item => {
			return (item.r === r && item.c === c)
		})
		return celldata
	}

	getCellDatas() {
		return this.celldata;
	}

	removeCellData(r, c) {
		let delIndex
		this.celldata.forEach((item, index) => {
			if (item.r === r && item.c === c) {
				delIndex = index
			}
		})
		this.celldata.splice(delIndex, 1)
	}

	getIndex() {
		return this.index;
	}
	getConfig() {
		return this.config;
	}

}